package goodbaby.dklt.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.FileUtil;
import com.classic.core.utils.ImageUtils;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.tgd.gbb.uikit.ui.dialog.BottomSelectDialog;
import com.tgd.gbb.uikit.ui.dialog.WLQQDataPicker;
import com.tgd.gbb.uikit.ui.dialog.WLQQHeightPicker;
import com.tgd.gbb.uikit.ui.dialog.WLQQSexPicker;
import com.tgd.gbb.uikit.ui.dialog.WLQQWeightPicker;
import com.tgd.gbb.uikit.ui.widget.asyncimageview.CircleImageView;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.bean.ImageBean;
import goodbaby.dklt.bean.UserInfo;

/**
 * Created by Jayden on 2016/5/4 11:34.
 *
 * @version V1.0
 * @Title: UserInfoActivity
 * @Description: ${todo}
 */
public class UserInfoActivity extends BaseActivity {
    public static final int ACTION_TYPE_ALBUM = 1;
    public static final int ACTION_TYPE_CAMERA = 2;
    private String birthday;
    private String currentDate;
    private BottomSelectDialog dialog;
    private EditText etName;
    private EditText etSport;
    private File imgFile;
    private ImageView ivBack;
    private CircleImageView ivHeadImg;
    private int mHeight;
    private int mSex;
    private double mWeight;
    private String nickName;
    private RelativeLayout rlBrithday;
    private RelativeLayout rlHeight;
    private RelativeLayout rlSex;
    private RelativeLayout rlWeight;
    private String school;
    private String sport;
    private String theLarge;
    private String theThumbnail;
    private TextView tvBrithDay;
    private TextView tvHeight;
    private TextView tvSchool;
    private TextView tvSex;
    private TextView tvSubmit;
    private TextView tvTitle;
    private TextView tvWeight;
    private String userImgPath;
    private PopupWindow sexPopupWindow;
    private PopupWindow weightPopupWindow;
    private PopupWindow heightPopupWindow;
    private PopupWindow popupWindow;
    private final Handler handler = new Handler() {
        public void handleMessage(Message paramAnonymousMessage) {
            if ((paramAnonymousMessage.what == 1) && (paramAnonymousMessage.obj != null)) {
                ivHeadImg.setImageBitmap((Bitmap) paramAnonymousMessage.obj);
                requestImageViewUpload((Bitmap) paramAnonymousMessage.obj);
            }
        }
    };


    private void getUserInfo() {
        ActionHelp.gbbQueryUserInfo(this, new ObjectCallback<UserInfo>() {

            public void onError(int paramAnonymousInt) {
            }

            public void onError(int paramAnonymousInt, String paramAnonymousString) {
                super.onError(paramAnonymousInt, paramAnonymousString);
            }

            public void onSuccess(UserInfo paramAnonymousUserInfo) {
                birthday = paramAnonymousUserInfo.getChildrenBirthday();
                mSex = Integer.parseInt(paramAnonymousUserInfo.getChildrenSex());
                mHeight = Integer.parseInt(paramAnonymousUserInfo.getHeight());
                mWeight = Double.parseDouble(paramAnonymousUserInfo.getWeight());
                initText();
            }

            @Override
            public Type getType() {
                return new TypeToken<UserInfo>() {
                }.getType();
            }
        });
    }

    private void goToSelectPicture(int position) {
        switch (position) {
            case ACTION_TYPE_ALBUM:
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);

                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
                }
                break;
            case ACTION_TYPE_CAMERA:
                // 判断是否挂载了SD卡
                String savePath = "";
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    savePath = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/goodbaby/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }
                }

                // 没有挂载SD卡，无法保存文件
                if (StringUtil.isEmpty(savePath)) {
                    //AppContext.showToastShort("无法保存照片，请检查SD卡是否挂载");
                    return;
                }

                String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                        .format(new Date());
                String fileName = "osc_" + timeStamp + ".jpg";// 照片命名
                File out = new File(savePath, fileName);
                Uri uri = Uri.fromFile(out);

                theLarge = savePath + fileName;// 该照片的绝对路径

                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent,
                        ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
                break;
            default:
                break;
        }
    }


    private void initText() {
        Picasso.with(this).load(userImgPath).into(ivHeadImg);
        etName.setText(nickName);
        etSport.setText(sport);
        if (mSex == 0) {
            tvSex.setText("女");
        } else {
            tvSex.setText("男");
        }

        tvBrithDay.setText(birthday);
        tvHeight.setText(mHeight + "cm");
        tvWeight.setText(mWeight + "kg");
        tvSchool.setText(school);

    }

    private void submit() {
        final String str = this.etName.getText().toString().trim();
        final int i = Integer.parseInt(this.etSport.getText().toString().trim());
        Date localDate = new Date();
        this.currentDate = new SimpleDateFormat("yyyy-MM-dd").format(localDate);
        Long localLong1 = Long.valueOf(this.currentDate.replaceAll("[-\\s:]", ""));
        Long localLong2 = Long.valueOf(this.birthday.replaceAll("[-\\s:]", ""));
        if (localLong1.longValue() < localLong2.longValue()) {
            ToastUtil.showToast(this, "请输入正确的生日");
            return;
        }
        if ((this.mHeight > 150) || (this.mHeight <= 0)) {
            ToastUtil.showToast(this, "请输入正确的身高");
            return;
        }
        if ((this.mWeight > 50.0D) || (this.mWeight <= 0.0D)) {
            ToastUtil.showToast(this, "请输入正确的体重");
            return;
        }
        if (StringUtil.isEmpty(str)) {
            ToastUtil.showToast(this, "请输入宝贝昵称");
            return;
        }
        ActionHelp.gbbUserInfo(this, str, birthday, mSex, mHeight, mWeight, i, new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
                ToastUtil.showToast(UserInfoActivity.this, "修改失败");
            }

            public void onError(int paramAnonymousInt, String paramAnonymousString) {
                super.onError(paramAnonymousInt, paramAnonymousString);
                ToastUtil.showToast(UserInfoActivity.this, "修改失败");
            }

            public void onSuccess(String paramAnonymousString) {
                ToastUtil.showToast(UserInfoActivity.this, "修改成功");
                GbbPreferences.saveNickName(str);
                GbbPreferences.saveSObject(i + "");
                finish();
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    public void HeightDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        //right_pop為泡泡的布局
        //View view = mLayoutInflater.inflate(R.layout.datetime_popupwindows, null);
        View view = mLayoutInflater.inflate(R.layout.popupwindows_height, null);
        WLQQHeightPicker localWLQQHeightPicker = (WLQQHeightPicker) view.findViewById(R.id.heightpicker);
        String str1 = tvHeight.getText().toString().trim();
        String str2;
        if (str1.length() == 4) {
            str2 = str1.substring(0, 2);
        } else {
            str2 = str1.substring(0, 3);
        }
        localWLQQHeightPicker.setDate(Integer.parseInt(str2));
        localWLQQHeightPicker.init(new HeightCallBack());
        this.heightPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.heightPopupWindow.setFocusable(true);
        this.heightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        this.heightPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.heightPopupWindow.setOutsideTouchable(true);
        this.heightPopupWindow.showAsDropDown(paramView);
    }

    public void SexDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        //right_pop為泡泡的布局
        //View view = mLayoutInflater.inflate(R.layout.datetime_popupwindows, null);
        View view = mLayoutInflater.inflate(R.layout.popupwindows_sex, null);
        WLQQSexPicker localWLQQSexPicker = (WLQQSexPicker) view.findViewById(R.id.sexpicker);
        localWLQQSexPicker.setDate(1);
        localWLQQSexPicker.init(new SexCallBack());
        this.sexPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.sexPopupWindow.setFocusable(true);
        this.sexPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        this.sexPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.sexPopupWindow.setOutsideTouchable(true);
        this.sexPopupWindow.showAsDropDown(paramView);
    }

    public void WeightDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        //right_pop為泡泡的布局
        //View view = mLayoutInflater.inflate(R.layout.datetime_popupwindows, null);
        View view = mLayoutInflater.inflate(R.layout.popupwindows_weight, null);
        WLQQWeightPicker localWLQQWeightPicker = (WLQQWeightPicker) view.findViewById(R.id.weightpicker);
        localWLQQWeightPicker.setDate(Float.parseFloat(this.tvWeight.getText().toString().trim().substring(0, 4)));
        localWLQQWeightPicker.init(new WeightCallBack());
        this.weightPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.weightPopupWindow.setFocusable(true);
        this.weightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        this.weightPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.weightPopupWindow.setOutsideTouchable(true);
        this.weightPopupWindow.showAsDropDown(paramView);
    }

    public void babyBirthdayDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        //right_pop為泡泡的布局
        //View view = mLayoutInflater.inflate(R.layout.datetime_popupwindows, null);
        View view = mLayoutInflater.inflate(R.layout.popupwindows_time, null);
        WLQQDataPicker localWLQQDataPicker = (WLQQDataPicker) view.findViewById(R.id.timepicker);
        localWLQQDataPicker.setDate(new Date().getTime());
        localWLQQDataPicker.init(new MyCallBack());
        this.popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        this.popupWindow.setFocusable(true);
        this.popupWindow.setBackgroundDrawable(new BitmapDrawable());
        this.popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.popupWindow.setOutsideTouchable(true);
        this.popupWindow.showAsDropDown(paramView);
    }

    public int getLayoutResId() {
        return R.layout.activity_user_info;
    }

    public void initData() {
        super.initData();
        this.userImgPath = GbbPreferences.getHeadImg();
        this.nickName = GbbPreferences.getNickName();
        this.sport = GbbPreferences.getSObject();
        this.school = GbbPreferences.getClassName();
    }

    public void initView() {
        super.initView();
        tvTitle = (TextView) findViewById(R.id.tv_common_title);
        tvTitle.setText("基础信息");
        ivBack = (ImageView) findViewById(R.id.iv_common_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvSubmit = (TextView) findViewById(R.id.tv_common_leave_history);
        tvSubmit.setVisibility(View.VISIBLE);
        tvSubmit.setText("保存");
        tvSubmit.setOnClickListener(this);
        ivHeadImg = (CircleImageView) findViewById(R.id.iv_change_headimg);
        ivHeadImg.setOnClickListener(this);
        etName = (EditText) findViewById(R.id.et_username);
        etSport = (EditText) findViewById(R.id.et_sport);
        etSport.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable paramAnonymousEditable) {
            }

            public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
            }

            public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
                if (StringUtil.isEmpty(paramAnonymousCharSequence.toString())) ;
                for (int i = 0; ; i = Integer.parseInt(paramAnonymousCharSequence.toString())) {
                    if (i > 20000) {
                        ToastUtil.showToast(UserInfoActivity.this, "运动目标不能超过20000");
                        UserInfoActivity.this.etSport.setText("20000");
                    }
                    return;
                }
            }
        });
        rlSex = (RelativeLayout) findViewById(R.id.rl_sex);
        rlBrithday = (RelativeLayout) findViewById(R.id.rl_birthday);
        rlWeight = (RelativeLayout) findViewById(R.id.rl_weight);
        rlHeight = (RelativeLayout) findViewById(R.id.rl_height);
        rlSex.setOnClickListener(this);
        rlBrithday.setOnClickListener(this);
        rlWeight.setOnClickListener(this);
        rlHeight.setOnClickListener(this);
        tvSex = (TextView) findViewById(R.id.tv_sex);
        tvBrithDay = (TextView) findViewById(R.id.tv_date);
        tvWeight = (TextView) findViewById(R.id.tv_weight);
        tvHeight = (TextView) findViewById(R.id.tv_height);
        tvSchool = (TextView) findViewById(R.id.tv_school);
        getUserInfo();
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode,
                                 final Intent imageReturnIntent) {
        if (resultCode != Activity.RESULT_OK)
            return;
        new Thread() {
            private String selectedImagePath;

            @Override
            public void run() {
                Bitmap bitmap = null;

                if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) {
                    if (imageReturnIntent == null)
                        return;
                    Uri selectedImageUri = imageReturnIntent.getData();
                    if (selectedImageUri != null) {
                        selectedImagePath = ImageUtils.getImagePath(
                                selectedImageUri, UserInfoActivity.this);
                    }

                    if (selectedImagePath != null) {
                        theLarge = selectedImagePath;
                    } else {
                        bitmap = ImageUtils.loadPicasaImageFromGalley(
                                selectedImageUri, UserInfoActivity.this);
                    }

                    if (StringUtil
                            .isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                        String imaName = FileUtil.getFileName(theLarge);
                        if (imaName != null)
                            bitmap = ImageUtils.loadImgThumbnail(UserInfoActivity.this,
                                    imaName,
                                    MediaStore.Images.Thumbnails.MICRO_KIND);
                    }
                    if (bitmap == null && !StringUtil.isEmpty(theLarge))
                        bitmap = ImageUtils
                                .loadImgThumbnail(theLarge, 100, 100);
                } else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA) {
                    // 拍摄图片
                    if (bitmap == null && !StringUtil.isEmpty(theLarge)) {
                        bitmap = ImageUtils
                                .loadImgThumbnail(theLarge, 100, 100);
                    }
                }

                if (bitmap != null) {// 存放照片的文件夹
                    String savePath = Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/goodbaby/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtil.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 判断是否已存在缩略图
                    if (largeFileName.startsWith("thumb_")
                            && new File(largeFilePath).exists()) {
                        theThumbnail = largeFilePath;
                        imgFile = new File(theThumbnail);
                    } else {
                        // 生成上传的800宽度图片
                        String thumbFileName = "thumb_" + largeFileName;
                        theThumbnail = savePath + thumbFileName;
                        if (new File(theThumbnail).exists()) {
                            imgFile = new File(theThumbnail);
                        } else {
                            try {
                                // 压缩上传的图片
                                ImageUtils.createImageThumbnail(UserInfoActivity.this,
                                        theLarge, theThumbnail, 800, 80);
                                imgFile = new File(theThumbnail);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }

    public void requestImageViewUpload(Bitmap paramBitmap) {
        String str = ImageUtils.bitmapToBase64(paramBitmap);
        ActionHelp.gbbUploadHeadImg(this, str + "#jpg", new ObjectCallback<ImageBean>() {

            public void onError(int paramAnonymousInt) {
            }

            public void onError(int paramAnonymousInt, String paramAnonymousString) {
                super.onError(paramAnonymousInt, paramAnonymousString);
            }

            public void onSuccess(ImageBean paramAnonymousImageBean) {
                ToastUtil.showToast(UserInfoActivity.this, "头像上传成功");
                GbbPreferences.saveHeadImg(paramAnonymousImageBean.getImagePath());
            }

            @Override
            public Type getType() {
                return new TypeToken<ImageBean>() {
                }.getType();
            }
        });
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                return;
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.tv_common_leave_history:
                submit();
                break;
            case R.id.iv_change_headimg:
                dialog = new BottomSelectDialog(this, new BottomSelectDialog.onSelectSexListener() {
                    public void onSelect(int paramAnonymousInt) {
                        goToSelectPicture(paramAnonymousInt);
                    }
                });
                dialog.show();
                break;
            case R.id.rl_sex:
                SexDialog(rlSex);
                break;
            case R.id.rl_birthday:
                babyBirthdayDialog(rlBrithday);
                break;
            case R.id.rl_weight:
                WeightDialog(rlBrithday);
                break;
            case R.id.rl_height:
                HeightDialog(rlBrithday);
                break;
        }

    }

    class HeightCallBack
            implements WLQQHeightPicker.CallBack {
        public void Cancel() {
            UserInfoActivity.this.heightPopupWindow.dismiss();
        }

        public void ConfirmAndGetData(int paramInt) {
            mHeight = paramInt;
            tvHeight.setText(mHeight + "cm");
            heightPopupWindow.dismiss();
        }
    }

    public class MyCallBack
            implements WLQQDataPicker.CallBack {
        public MyCallBack() {
        }

        public void Cancel() {
            UserInfoActivity.this.popupWindow.dismiss();
        }

        public void ConfirmAndGetData(String paramString, int paramInt1, int paramInt2, int paramInt3) {
            birthday = paramString;
            tvBrithDay.setText(birthday);
            popupWindow.dismiss();
        }
    }

    class SexCallBack
            implements WLQQSexPicker.CallBack {

        public void Cancel() {
            UserInfoActivity.this.sexPopupWindow.dismiss();
        }

        public void ConfirmAndGetData(int paramInt) {
            mSex = paramInt;
            if (mSex == 0)
                tvSex.setText("女");
            else {
                tvSex.setText("男");
            }
            sexPopupWindow.dismiss();
        }
    }

    class WeightCallBack
            implements WLQQWeightPicker.CallBack {

        public void Cancel() {
            UserInfoActivity.this.weightPopupWindow.dismiss();
        }

        public void ConfirmAndGetData(double paramDouble) {
            mWeight = paramDouble;
            tvWeight.setText(mWeight + "kg");
            weightPopupWindow.dismiss();
        }
    }
}
